package com.sqxgg.drugstore.filter;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class LogCostFilter implements Filter {
    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        LOGGER.info("过滤器1111");
        String requestURL = ((HttpServletRequest) servletRequest).getRequestURL().toString();
        String contentType = servletRequest.getContentType();
        String paramJson  = "";
        if ("application/json".equals(contentType)) {
            paramJson = this.getJsonParam((HttpServletRequest) servletRequest);
        } else {
            paramJson = JSON.toJSONString(servletRequest.getParameterMap());
        }
        LOGGER.info("【Filter过滤用户操作日志】{}",paramJson);

        LOGGER.info("start");
        filterChain.doFilter(servletRequest,servletResponse);
        LOGGER.info("end");
        System.out.println("Execute cost="+(System.currentTimeMillis()-start));
    }

    @Override
    public void destroy() {
        LOGGER.info("过滤器2222");
    }
    /**
     * 获取Json数据
     *
     * @param request
     * @return
     */
    private String getJsonParam(HttpServletRequest request) {
        String jsonParam = "";
        ServletInputStream inputStream = null;
        try {
            int contentLength = request.getContentLength();
            if (!(contentLength < 0)) {
                byte[] buffer = new byte[contentLength];
                inputStream = request.getInputStream();
                for (int i = 0; i < contentLength; ) {
                    int len = inputStream.read(buffer, i, contentLength);
                    if (len == -1) {
                        break;
                    }
                    i += len;
                }
                jsonParam = new String(buffer, "utf-8");
            }
        } catch (IOException e) {
            LOGGER.error("参数转换成json异常g{}", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("参数转换成json异常s{}", e);
                }
            }
        }
        return jsonParam;
    }

}
